﻿#include "Player.h"



Player::Player(QTcpSocket *socket)
{
    mName = "";
    mRoom = FIR_DEFAULT_ROOM;
    mBlack = true;
    mSocket = socket;

    connect(mSocket, &QTcpSocket::readyRead, this, &Player::slotTcpMsg);
}

void Player::slotTcpMsg()
{
    int nHeaderLen = sizeof(MSG_HEADER);
    if (mSocket->bytesAvailable() <= 0)
    {
        return;
    }
    QByteArray data = mSocket->readAll();
    mData += data;

    while(1)
    {
        if (mData.size() < nHeaderLen)
        {
            //当前接收内容不足一个消息头长度，无法处理继续接收
            return;
        }
        MSG_HEADER* pMsg = (MSG_HEADER*)mData.data();
        if (mData.size() < nHeaderLen + pMsg->nDataLen)
        {
            //当前接收内容足一个消息头，但不足解析本消息需要的总长度(头长度+头里指定的数据长度)
            return;
        }

        //判断是不是服务器认识的消息
        if (pMsg->nType == MQ_LOGON ||
            pMsg->nType == MQ_MOVE ||
            pMsg->nType == MQ_SUCCESS ||
            pMsg->nType == MQ_SAY ||
            pMsg->nType == MQ_HEARTBEAT)
		{
			emit sigRecvMsg((char*)(pMsg), pMsg->nDataLen);
        }
        else
        {
            //不认识的消息
            mData.clear();
            return;
        }
        mData.remove(0, nHeaderLen + pMsg->nDataLen);
    }
}

bool Player::IsHeartbeatTimeout()
{
    if (mHeartBeatTime.msecsTo(QDateTime::currentDateTime()) >= 5000)
	{
		return true;
    }
	return false;
}

void Player::UpdateHeartbeat()
{
	mHeartBeatTime = QDateTime::currentDateTime();
}

bool Player::Send(MSG_HEADER msg)
{
    mSocket->write((char*)&msg,sizeof(MSG_HEADER));
    mSocket->flush();
    return true;
}

bool Player::Send(MSG_HEADER msg, char* pData, int nDataLen)
{
    int nLen = sizeof(MSG_HEADER) + nDataLen;
    char* buf = new char[nLen];
    memset(buf,0,nLen);

    memcpy(buf,(char*)&msg,sizeof(MSG_HEADER));
    memcpy(buf + sizeof(MSG_HEADER),pData,nDataLen);

    mSocket->write(buf, nLen);
    mSocket->flush();

    delete []buf;
    return true;
}
